package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //1.上传图片到minio中
        // 校验参数
        if (file == null || file.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 上传文件
        // 生成UUID文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 上传到minio
        String fileUrl;
        try {
            fileUrl = fileStorageService.uploadImgFile("", fileName + fileType, file.getInputStream());
            log.info("图片上传成功，fileUrl:{}", fileUrl);
        } catch (IOException e) {
            log.error("图片上传失败");
            throw new RuntimeException(e);
        }

        // 保存图片信息到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());

        save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.校验参数
        dto.checkParam();
        //2.分页查询
        IPage pageCheck=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //2.1是否收藏
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //2.2 按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //2.3 按照时间排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //2.4 查询
        pageCheck = page(pageCheck, lambdaQueryWrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageCheck.getTotal());
        responseResult.setData(pageCheck.getRecords());
        return responseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {

        // 1. 校验参数
        if(id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 校验素材是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null) {
            // 数据不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 3. 要删除的素材的user_id与当前用户id是否一致
        // 用户仅可删除自己的素材
        Integer userId = WmThreadLocalUtil.getUser().getId();
        if(!userId.equals(wmMaterial.getUserId())) {
            return ResponseResult.errorResult(501, "文件删除失败1");
        }

        // 4.判断素材与文章之间是否存在引用关系
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId, id);
        int count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
        if(count > 0) {
            return ResponseResult.errorResult(501, "文件删除失败");
        }

        // 5. 删除图片
        // 删除minIO里的数据
        fileStorageService.delete(wmMaterial.getUrl());
        // 删除数据库里的数据
        boolean b = removeById(id);

        if(b) {
            // 删除成功
            System.out.println("图片素材删除成功！");
            return ResponseResult.okResult(wmMaterial);
        } else {
            // 删除失败
            return ResponseResult.errorResult(501, "文件删除失败");
        }
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        // 检查参数
        if(id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 校验素材是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null) {
            // 数据不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 取消收藏
        wmMaterial.setIsCollection((short) 0);
        updateById(wmMaterial);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        // 检查参数
        if(id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 校验素材是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null) {
            // 数据不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 收藏素材
        wmMaterial.setIsCollection((short) 1);
        updateById(wmMaterial);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
